package com.xb.loan.log.impl;

import com.xb.loan.log.IUserLogService;
import com.xb.loan.log.bean.UserLogVO;
import com.xb.loan.log.constant.IenumConstants;
import com.xb.loan.log.dao.UserLogDao;
import com.xb.loan.log.dao.bean.UserLog;
import com.xb.loan.util.cache.redis.comm.FormatOperation;
import com.xb.loan.util.common.ObjectOperation;
import com.xb.loan.util.log.DefaultLoggerFacotry;
import com.xb.loan.util.strategy.TableNoAllocatorFactory;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("userLogService")
public class UserLogServiceImpl implements IUserLogService {
    
    public static final Logger logger = DefaultLoggerFacotry.getLogger(UserLogServiceImpl.class);
    
    @Autowired
    private UserLogDao userLogDao;

	@Override
	public void insertUserLog(UserLogVO userLogVO) {
		
		UserLog userLog = ObjectOperation.convertByClasses(userLogVO, UserLog.class);
        String id =  FormatOperation.assemblySeq("common", 4, FormatOperation.formatDateToYMDHms(new Date()), "");
        userLog.setLogId(id);
		userLog.setTableId(getTableId(userLogVO.getUserId()));
		userLogDao.insertUserLog(userLog);
	}
	
    /**
     * 查询日志列表
     **/
    @Override
    public List<UserLogVO> queryUserLogList(String userId, String logModel, String endTime, String startTime, int from, int pageSize) {
      
    	Map<String,Object> params = new HashMap<String,Object>();
        params.put("tableId", getTableId(userId));
        params.put("userId", userId);
        params.put("logModule", logModel);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("from", from);
        params.put("pageSize", pageSize);
        List<UserLog> logs = userLogDao.queryUserLogList(params);
        return ObjectOperation.convertByClassesList(logs, UserLogVO.class);
    }

    /**
     * 查询日志总数
     **/
    @Override
    public int queryUserLogListCount(String userId, String logModel, String endTime, String startTime) {
      
    	Map<String,Object> params = new HashMap<String,Object>();
        params.put("tableId", getTableId(userId));
        params.put("userId", userId);
        params.put("logModule", logModel);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        int total = userLogDao.queryUserLogListCount(params);
        return total;
    }

    public int getTableId(String userId) {

        return Integer.parseInt(TableNoAllocatorFactory.getAllocator(IenumConstants.TableNoAllocator.USER_LOG.getCode()).getTableNo(userId));
    }
    
}
